import React,{useState,useEffect,useMemo,useCallback,useRef,createRef,useReducer} from 'react'

// 初始数据
const cartlist = [
    { id:1, name: "goods1", price: 98, qty: 2 },
    { id:2, name: "goods2", price: 198, qty: 2 },
    { id:3, name: "goods3", price: 998, qty: 1 },
];

// 用户修改state的方法
const reducer = function(state,action){
    // state: 最新数据
    // action: 命令，格式为：{type}

    switch(action.type){
        // 增加商品
        case 'add':

            return [action.goods,...state]

        // 删除商品
        case 'remove':
            return state.filter(item=>item.id != action.id)

        // 修改数量
        case 'changeqty':
            return state.map(item=>{
                if(item.id === action.id){
                    item.qty = action.qty
                }
                return item
            })

        // 清空购物车
        case 'clear':
            return []
    }
    
}

function UseReducer(props){

    // 购物车商品数据
    const [state,dispatch] = useReducer(reducer,cartlist)

    // 添加商品
    // const action = {type:'add',goods:{id:10,name:'huawei mate50 pro',price:4999}}
    // dispatch(action)
    // dispatch({type:'remove',id:1})
    // dispatch({type:'changeqty',id:1,qty:10})
    // dispatch({type:'clear'})

    // 计算总价
    const totalPrice = useMemo(()=>{
        return state.reduce((prev,item)=>prev+item.qty*item.price,0)
    },[state])

    const changeQty = useCallback((id,e)=>{
        dispatch({type:'changeqty',id,qty:e.target.value})
    },[])

    const removeItem = useCallback((id)=>{
        dispatch({type:'remove',id})
    },[])
    const clear = useCallback(()=>{
        dispatch({type:'clear'})
    },[])

    return (
        <div>
            <h4>useReducer</h4>
            <ul>
                {
                    state.map(item=><li key={item.id}>
                        <h4>{item.name}</h4>
                        <p>价格：{item.price}</p>
                        <p><input type="number" value={item.qty} onChange={changeQty.bind(null,item.id)} /></p>
                        <button onClick={removeItem.bind(null,item.id)}>删除</button>
                    </li>)
                }
                
            </ul>
            
            <button onClick={clear}>清空</button>
            总计：{totalPrice}
        </div>
    )
}

export default UseReducer;